//
//  RoomViewController.m
//  LiveEducation
//
//  Created by Liu,Qingcan on 2017/4/17.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "RoomViewController.h"
#import "Masonry.h"
#import "StreamPushViewController.h"
#import "UIView+LEBezierPath.h"

#import "Room+CoreDataClass.h"
#import "RoomModel.h"
#import "AddLiveUrlAddress.h"
#import "AddRoomApi.h"
#import "UserRoomModel.h"
#import "CategoryModel.h"
#import "LECategoryItem.h"

#define NavBarH 64

//#import <IJKMediaFramework/IJKFFMoviePlayerController.h>

#define BaseUrl @"rtmp://player.daniulive.com:1935/hls"


@interface RoomViewController () <UIPickerViewDelegate,UIPickerViewDataSource>
{
    DNVideoStreamingQuality streamQuality;
    NSInteger               audio_opt_;
    NSInteger               video_opt_;
    Boolean                 is_recorder_;
    Boolean                 is_beauty_;
}

@property (nonatomic,assign)NSInteger roomId;
@property (nonatomic,assign)NSInteger chooseCateId;
//category数据源
@property(nonatomic,strong)NSArray *categoryArray;
@property(nonatomic,strong)NSArray *categoryIdArray;


@property (nonatomic,strong)UIView *navTitleView;
@property (nonatomic,strong)UIButton *backBtn;
@property (nonatomic,strong)UIButton *finishBtn;


//课程相关等属性 -- 只要这两个属性
@property (nonatomic,strong)UITextField *titleField;
@property (nonatomic,strong)UILabel *titleLabel;
//@property (nonatomic,strong)UITextField *zhuboField;
@property (nonatomic,strong)UIPickerView *categoryPicker;
@property (nonatomic,strong)UIButton *chooseBtn;
@property (nonatomic,strong)UILabel *chooseLabel;
@property (nonatomic,strong)UILabel *separateLabel;
@property (nonatomic,strong)UILabel *separateChooseLabel;
@property (nonatomic,strong)NSString *categoryName;

@property (nonatomic,strong)UIImageView *backImage;


@property (nonatomic,strong)NSString *stremUrl;


@property (nonatomic,assign,getter=isChooseBtnSelected) BOOL chooseBtnSelected;



//@property(nonatomic, retain) id<IJKMediaPlayback> player;

//session
//@property (nonatomic, strong) PLMediaStreamingSession *session;


@end

@implementation RoomViewController
#pragma mark life circle

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.view.backgroundColor = [UIColor colorWithRed:255.f/255 green:255.f/255 blue:255.f/255 alpha:0.6f];
    self.view.backgroundColor =  [UIColor colorWithWhite:1.f alpha:1.8f];

//    UIView *bgView = [[UIView alloc]initWithFrame:self.view.bounds];
////    self.view.alpha = 0.5;
//    bgView.backgroundColor =  [UIColor colorWithWhite:1.f alpha:0.5f];
//    [self.view addSubview:bgView];
    
//    [UIApplication sharedApplication].keyWindow.backgroundColor = [UIColor whiteColor];
    
//    UIColor *color = [UIColor whiteColor];
//    self.view.backgroundColor = [color colorWithAlphaComponent:0.5];
    //    self.view.opaque = NO;
    
    [self.view addSubview:self.backImage];
    [self.view addSubview:self.navTitleView];
//    [self.navTitleView addSubview:self.finishBtn];
    [self.navTitleView addSubview:self.backBtn];
    
    [self.view addSubview:self.categoryPicker];
    [self.view addSubview:self.titleField];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.chooseBtn];
    [self.view addSubview:self.chooseLabel];
    [self.view addSubview:self.separateLabel];
    [self.view addSubview:self.separateChooseLabel];
    [self.view addSubview:self.categoryPicker];
    [self.view addSubview:self.finishBtn];
    [self.view sendSubviewToBack:self.backImage];
    
    NSString *currentTime = [self getCurrentTime];

}



- (void)loadView
{
    // If you create your views manually, you MUST override this method and use it to create your views.
    // If you use Interface Builder to create your views, then you must NOT override this method.
    
    //默认标清分辨率
    streamQuality = DN_VIDEO_QUALITY_MEDIUM;
    //默认采集音视频
    audio_opt_ = 1;
    video_opt_ = 1;
    //默认不录像
    is_recorder_  = false;
    //默认美颜
    is_beauty_ = true;
    
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    //[UIScreen bounds]
//    self.view.backgroundColor = [UIColor whiteColor];
//    self.view.backgroundColor = [UIColor colorWithRed:255.f/255 green:255.f/255 blue:255.f/255 alpha:0.6f];
//    self.view.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.5f];
    
    
}

//- (void)didReceiveMemoryWarning {
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}
//
//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:YES];
//    
////    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////        [self dismissViewControllerAnimated:YES completion:nil];
////    });
//}


- (void)viewDidLayoutSubviews{
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_navTitleView.mas_left).with.offset(10);
        make.width.mas_equalTo(40);
        make.height.equalTo(_navTitleView.mas_height).with.offset(-25);
        make.centerY.equalTo(_navTitleView.mas_centerY).offset(10);
    }];
    
//    [self.finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(_navTitleView.mas_right).with.offset(-10);
//        make.width.mas_equalTo(80);
//        make.height.equalTo(_navTitleView.mas_height).with.offset(-25);
//        make.centerY.equalTo(_navTitleView.mas_centerY).offset(10);
//    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_navTitleView.mas_left).with.offset(50);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(50);
        make.top.equalTo(_navTitleView.mas_bottom).offset(100);
    }];
    
    [self.titleField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleLabel.mas_right).with.offset(20);
        make.right.equalTo(_navTitleView.mas_right).with.offset(-50);
        make.height.mas_equalTo(50);
        make.top.equalTo(_navTitleView.mas_bottom).offset(100);
    }];
    
    [self.separateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleField.mas_left);
        make.right.equalTo(_titleField.mas_right).offset(-10);
        make.height.mas_equalTo(1);
        make.top.equalTo(_titleField.mas_bottom).offset(-4);
    }];
    
    
    
    
    
    [self.chooseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleLabel.mas_left);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(50);
        make.top.equalTo(_titleLabel.mas_bottom).offset(20);
    }];
    
    [self.chooseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_chooseBtn.mas_right).with.offset(20);
        make.right.equalTo(_navTitleView.mas_right).with.offset(-50);
        make.height.mas_equalTo(50);
        make.top.equalTo(_titleLabel.mas_bottom).offset(20);
    }];
    [self.separateChooseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_chooseLabel.mas_left);
        make.right.equalTo(_chooseLabel.mas_right).offset(-10);
        make.height.mas_equalTo(1);
        make.top.equalTo(_chooseLabel.mas_bottom).offset(-4);
    }];
    
    [self.categoryPicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_chooseBtn.mas_right).with.offset(20);
        make.right.equalTo(_navTitleView.mas_right).with.offset(-50);
        make.height.mas_equalTo(100);
        make.top.equalTo(_titleLabel.mas_bottom).offset(30);
    }];
    
    [self.finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_chooseBtn.mas_left);
        make.right.equalTo(_navTitleView.mas_right).with.offset(-50);
        make.height.mas_equalTo(45);
        make.top.equalTo(_chooseLabel.mas_bottom).offset(100);
    }];
    
}


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


#pragma mark UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.categoryArray.count;
}

#pragma mark UIPickerViewDelegate

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    return 100;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 40;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [self.categoryArray objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    self.categoryName = [self.categoryArray objectAtIndex:row];
    NSNumber *choosenum = [self.categoryIdArray objectAtIndex:row];
    
    self.chooseCateId = choosenum.integerValue;
    self.chooseLabel.text = self.categoryName;
}



#pragma event response
- (void)finishButtonClicked:(UIButton *)sender{
    NSString* publishURL;
//    
//    NSString* inputVal = [[self inputUrlText] text];
    
//    if ( inputVal.length < 7 || ([inputVal hasPrefix:@"rtmp://"] == NO))
//    {
        NSLog(@"incorrect publish url, use default url..");
        
        NSInteger randNumber = arc4random()%(1000000);
        
        NSString *strNumber = [NSString stringWithFormat:@"%ld", (long)randNumber];
        
//        NSString *baseURL = @"rtmp://player.daniulive.com:1935/hls/stream";
    
        publishURL = [ BaseUrl stringByAppendingString:@"/"];
        publishURL = [publishURL stringByAppendingString:strNumber];
    
//    }
//    else
//    {
//        publishURL = inputVal;
//    }
    
    NSLog(@"publishURL:%@", publishURL);
    if (!self.stremUrl) {
        self.stremUrl = publishURL;
    }
    
    if(self.roomId==0){//说明本界面初创
        
        
        //1.新增room
        AddRoomApi *addroomApi = [[AddRoomApi alloc]initWithCategoryId:self.chooseCateId title:self.titleField.text liveUrl:self.stremUrl];
        [addroomApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            //2.判断服务器状态码
            NSNumber *status = [dict objectForKey:@"statusCode"];
            
            if (status.integerValue == 1) {
                NSNumber *temp = dict[@"data"];
                self.roomId = temp.integerValue;
                NSLog(@"添加房间信息 -- 成功");
               
                
                
                
                //查询用户id
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSInteger userId = [defaults integerForKey:@"userId"];
                
//                //本地存入个人的直播房间信息，用以在个人界面展示
//                UserRoomModel *userRoomDao = [[UserRoomModel alloc]init];
//                User_Room *item = [NSEntityDescription insertNewObjectForEntityForName:@"User_Room" inManagedObjectContext:userRoomDao.persistence.currentContext];
//                
//                item.video_url = publishURL;
//                item.user_id = userId;
//                item.room_id = self.roomId;
//                [userRoomDao insertUser_RoomData:item];
                
                //和服务器交互
                AddLiveUrlAddress *api = [[AddLiveUrlAddress alloc]initWithUserId:userId roomId:self.roomId url:self.stremUrl];
                
                [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                    NSDictionary *dict = request.responseJSONObject;
                    //2.判断服务器状态码
                    NSNumber *status = [dict objectForKey:@"statusCode"];
                    
                    if (status.integerValue == 1) {
                        NSLog(@"添加直播地址信息 -- 成功");
                        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
                        [def setBool:YES forKey:@"user_add_new_room"];
                    }else{
                        NSLog(@"未能成功添加直播地址数据 the reason is : %@ ,%s",dict[@"statusMsg"],__FUNCTION__ );
                    }
                    
                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                    
                }];
                
            }else{
                //2.输出状态码
                NSLog(@"未能成功获得数据 the reason is : %@ ,%s",dict[@"statusMsg"],__FUNCTION__ );
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
        
        
    }
    
   

    
    
    
    
    
    
    StreamPushViewController * coreView =[[StreamPushViewController alloc]
                                          initParameter:self.stremUrl
                                          streamQuality:streamQuality
                                               audioOpt:audio_opt_
                                               videoOpt:video_opt_
                                             isRecorder:is_recorder_
                                               isBeauty:is_beauty_];
    [self presentViewController:coreView animated:YES completion:nil];
}

- (void)backButtonClicked:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)chooseCategory:(UIButton *)button{
    _chooseBtnSelected = !_chooseBtnSelected;
    
    if (_chooseBtnSelected) {
        [button setTitle:@"确定" forState:UIControlStateNormal];
        [UIView animateWithDuration:1.0 animations:^{
            self.categoryPicker.hidden = NO;
            self.separateChooseLabel.hidden = YES;
            self.chooseLabel.hidden = NO;
        }];
    }else{
        [button setTitle:@"选择分类" forState:UIControlStateNormal];
        [UIView animateWithDuration:1.0 animations:^{
            self.categoryPicker.hidden = YES;
            self.separateChooseLabel.hidden = NO;
        }];
    }
    
    
}


#pragma mark private
//获取当前时间
- (NSString *)getCurrentTime{

    NSDateFormatter *format = [[NSDateFormatter alloc]init];
//    [format setDateFormat:@"yyyy-MM-dd HH:mm"];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSString *currentTime = [format stringFromDate:[NSDate date]];
    NSLog(@"当前时间是： %@",currentTime);
    NSString *result = [NSString stringWithFormat:@"有效期至%@",currentTime];
    
    return currentTime;
}


#pragma mark getter

- (UIView *)navTitleView{
    if (!_navTitleView) {
        _navTitleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, NavBarH)];
        _navTitleView.backgroundColor = [UIColor colorWithRed:60/255.f green:157/255.f blue:189/255.f alpha:.7f];
    }
    return _navTitleView;
}

- (UIButton *)backBtn{
    if (!_backBtn) {
        
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_backBtn makeViewCircle];
        [_backBtn setBackgroundImage:[UIImage imageNamed:@"backImage"] forState:UIControlStateHighlighted];
        [_backBtn setTitle:@"退出" forState:UIControlStateNormal];
        
//        _backBtn.backgroundColor = [UIColor blueColor];
        _backBtn.contentMode = UIViewContentModeCenter;
        _backBtn.titleLabel.font = [UIFont systemFontOfSize:13.6f];
        
        [_backBtn addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _backBtn;
}

- (UIButton *)finishBtn{
    if (!_finishBtn) {
        _finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_finishBtn setBackgroundImage:[UIImage imageNamed:@"backImage"] forState:UIControlStateHighlighted];
        [_finishBtn setBackgroundColor:[UIColor orangeColor]];
        [_finishBtn setTitle:@"已创建好房间,马上进入直播间吧" forState:UIControlStateNormal];
        
        _finishBtn.titleLabel.font = [UIFont systemFontOfSize:14.6f];
        _finishBtn.contentMode = UIViewContentModeCenter;
        
        _finishBtn.layer.masksToBounds = YES;
        _finishBtn.layer.cornerRadius = 10;
        [_finishBtn addTarget:self action:@selector(finishButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _finishBtn;
}


- (UIPickerView *)categoryPicker{
    if (!_categoryPicker) {
        _categoryPicker = [[UIPickerView alloc]init];
        _categoryPicker.delegate = self;
        _categoryPicker.dataSource = self;
//        _categoryPicker.backgroundColor = [UIColor colorWithRed:240.f/255 green:240.f/255 blue:240.f/255 alpha:0.2f];
//        [_categoryPicker makeViewCircle];
        _categoryPicker.hidden = YES;
    }
    return _categoryPicker;
}

- (UIButton *)chooseBtn{
    if (!_chooseBtn) {
        _chooseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_chooseBtn setTitle:@"选择分类" forState:UIControlStateNormal];
        _chooseBtn.titleLabel.font = [UIFont systemFontOfSize:13.6f];
        _chooseBtn.tintColor =[UIColor colorWithRed:182.f/255 green:116.f/255 blue:147.f/255 alpha:1.f];
//        _chooseBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        _chooseBtn.backgroundColor =  [UIColor colorWithRed:150.f/255 green:150.f/255 blue:1500.f/255 alpha:.9f];
//        _chooseBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _chooseBtn.layer.masksToBounds = YES;
        _chooseBtn.layer.cornerRadius = 15;
        [_chooseBtn addTarget:self action:@selector(chooseCategory:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _chooseBtn;
}

- (UILabel *)chooseLabel{
    if (!_chooseLabel) {
        _chooseLabel = [[UILabel alloc]init];
        _chooseLabel.numberOfLines = 0;
        _chooseLabel.font = [UIFont systemFontOfSize:15.5f];
//        _chooseLabel.backgroundColor =  [UIColor colorWithRed:240.f/255 green:240.f/255 blue:240.f/255 alpha:0.5f];
//        _chooseLabel.hidden = YES;
//        _chooseLabel.text = @""
        
    }
    return _chooseLabel;
}

- (UITextField *)titleField{
    if(!_titleField){
        _titleField = [[UITextField alloc]init];
        _titleField.placeholder = @"请输入课程名称";
//        _titleField.textColor = [UIColor blackColor];
        _titleField.borderStyle = UITextBorderStyleNone;
        _titleField.rightViewMode = UITextFieldViewModeWhileEditing;
        
    }
    return _titleField;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.font = [UIFont systemFontOfSize:13.6f];
        _titleLabel.text = @"课程名称：";
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
//        _titleLabel.textColor = [UIColor whiteColor];
    }
    return _titleLabel;
}

- (UILabel *)separateLabel{
    if (!_separateLabel) {
        _separateLabel = [[UILabel alloc]init];
//        _separateLabel.font = [UIFont systemFontOfSize:13.6f];
        _separateLabel.backgroundColor = [UIColor blackColor];
    }
    return _separateLabel;
}

- (UILabel *)separateChooseLabel{
    if (!_separateChooseLabel) {
        _separateChooseLabel = [[UILabel alloc]init];
        //        _separateLabel.font = [UIFont systemFontOfSize:13.6f];
        _separateChooseLabel.backgroundColor = [UIColor blackColor];
        _separateChooseLabel.hidden = YES;
    }
    return _separateChooseLabel;
}


- (BOOL)isChooseBtnSelected{
    return  _chooseBtnSelected;
}


- (NSArray *)categoryArray{
    if (!_categoryArray) {
        _categoryArray = [[NSArray alloc]init];
        NSMutableArray *cateNameArr = [NSMutableArray array];
        NSMutableArray *cateIdArr = [NSMutableArray array];
        
//        _categoryArray = @[@"公务员",@"教育",@"村官",@"支书"];
        CategoryModel *cateDao = [[CategoryModel alloc]init];
        NSArray *arr = [cateDao selectAllData];
        for (LECategoryItem *cate in arr){
            [cateNameArr addObject:cate.name];
            [cateIdArr addObject:[NSNumber numberWithInt:cate.nid]];
        }
        _categoryArray = [cateNameArr copy];
        self.categoryIdArray = [cateIdArr copy];
        
        
    }
    return _categoryArray;
}

- (UIImageView *)backImage{
    if (!_backImage) {
        _backImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"createroom"]];
        _backImage.frame = [UIScreen mainScreen].bounds;
        _backImage.contentMode = UIViewContentModeScaleToFill;
    }
    return _backImage;
    
}

@end
